package cn.tedu.micro.demo.all.service;

import cn.tedu.micro.demo.all.dao.repository.CartRepository;
import cn.tedu.micro.demo.pojo.po.CartPO;
import cn.tedu.micro.demo.pojo.vo.CartVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService{
    @Autowired
    private CartRepository cartRepository;

    @Override
    public void addCart(Integer userId, String productCode, Integer count) {
        //调用数据层 写数据 入参封装成CartPO
        CartPO po=new CartPO();
        //封装属性
        po.setUserId(userId.toString());
        po.setProductCode(productCode);
        po.setCount(count);
        //针对 数据层 入参一般都是po 出参也是po
        cartRepository.save(po);
    }

    @Override
    public List<CartVO> listCart(String userId) {
        //1.调用仓储层查询 出参是List<CartPO>
        List<CartPO> cartPOS = cartRepository.findMyCarts(userId);
        //2.转化listVO list stream() filter() sorted() map() forEach()
        List<CartVO> collect = cartPOS.stream().map(po -> {
                //po 原集合中的每个元素
                CartVO vo = new CartVO();
                BeanUtils.copyProperties(po, vo);
                return vo;
            }
        ).collect(Collectors.toList());
        return collect;

    }

    @Override
    public void deleteCart(String userId, String productCode) {
        //delete from cart_tbl where user_id=#{userId} and product_code=#{productCode}
        cartRepository.deleteCart(userId,productCode);
    }
}
